import { useState } from 'react';
import styles from './index.module.less';
import { Button, Form, Input, message } from 'antd';
import { login } from '../../services/user';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

const Login = () => {
  const [form] = Form.useForm();
  const [logining, setLogining] = useState(false);
  const navigate = useNavigate();

  const handlerLogin = () => {
    setLogining(true);
    form.validateFields().then(async (values) => {
      try {
        const res = await login(values);
        if (res.data.code === 200) {
          message.success('操作成功');
          localStorage.setItem('token', res.data.data.token);
          navigate('/dashboard')
        } else {
          setLogining(false);
          message.warning(res.data.message);
        }
      } catch (error) {
        console.log(error);
      }
    }, () => {
      setLogining(false);
    });
  };

  return (
    <div className={styles.container}>
      <div className={styles.form}>
        <div className={styles.title}>购票系统</div>
        <Form
          form={form}
          labelCol={{ span: 0 }}
          wrapperCol={{ span: 24 }}
        >
          <Form.Item
            label=""
            name="userName"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input prefix={<UserOutlined />} placeholder='请输入用户名' />
          </Form.Item>
          <Form.Item
            label=""
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input
              prefix={<LockOutlined />}
              type="password"
              placeholder="请输入密码"
            />
          </Form.Item>
          <Form.Item>
            <Button style={{ width: '100%' }} loading={logining} onClick={handlerLogin} type="primary">登录</Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
